package com.zmytest.many2many;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created on 2018/12/27.
 *
 * @author zhangmingyu
 */
@RestController
@RequestMapping("/many2many")
public class Test4Controller {

    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private PermissionRepository permissionRepository;


    @GetMapping("/create")
    public void test(){

        Permission result = permissionRepository.save(new Permission("p1"));
        Permission result2 = permissionRepository.save(new Permission("p2"));
        List<Permission> permissions = new LinkedList<>();
        permissions.add(result);
        permissions.add(result2);

        Role role = new Role("r1");
        role.setPermissions(permissions);

        Role resultR = roleRepository.save(role);

        System.out.println("result "+resultR);
    }

    @GetMapping("/delete-relation/{permissionId}")
    public void test2(@PathVariable("permissionId") Integer permissionId){
        Role role = roleRepository.findOne(1);
        List<Permission> result = role.getPermissions().stream().filter(permission -> !permission.getId().equals(permissionId)).collect(Collectors.toList());
        role.setPermissions(result);
        roleRepository.save(role);
    }
}
